import React, {
  createContext,
  ReactNode,
  useState,
  useContext,
  useEffect,
  ReactElement,
} from 'react';
import type { Field, FieldStoreApi } from '@/types/store';

const FieldStoreContext = createContext<FieldStoreApi>({
  fieldList: [],
  addField: () => {},
  clearFields: () => {},
});

export const FieldStoreContextProvider = (
  props: FieldStoreApi & { children?: ReactNode },
): ReactElement => (
  <FieldStoreContext.Provider value={props}>
    {props.children}
  </FieldStoreContext.Provider>
);

export const useFieldStoreProvide = (): FieldStoreApi => {
  const [fieldList, setFieldList] = useState<Field[]>([]);

  const addField = (field: Field): void => {
    setFieldList((prev) => [...prev, field]);
  }

  const clearFields = (): void => {
    setFieldList([]);
  }

  useEffect(() => {
    setFieldList([
      {
        key: 'view',
        name: '景点'
      },
      {
        key: 'food',
        name: '美食'
      },
      {
        key: 'hotel',
        name: '酒店'
      },
      {
        key: 'massage',
        name: '按摩'
      },
      {
        key: 'ktv',
        name: 'KTV'
      },
    ]);
  }, []);

  return {
    fieldList,
    addField,
    clearFields,
  };
}

export const useFieldList = () => {
  return useContext(FieldStoreContext).fieldList;
}
